package org.csu.onlineedubackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.CourseLike;
import org.csu.onlineedubackend.mapper.CourseLikeMapper;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/courses")
@Slf4j
public class CourseLikeController {

    @Autowired
    private CourseLikeMapper courseLikeMapper;
    
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    /**
     * 添加课程收藏
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @param request HttpServletRequest
     * @return 操作结果
     */
    @PostMapping("/{courseId}/like")
    public CommonResponse<Boolean> addLike(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId,
            HttpServletRequest request) {
        log.info("添加课程收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("添加课程收藏失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("添加课程收藏失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 检查是否已收藏
            try {
                QueryWrapper<CourseLike> wrapper = new QueryWrapper<>();
                wrapper.eq("course_id", courseId).eq("student_id", studentId);
                Long count = courseLikeMapper.selectCount(wrapper);
                
                if (count != null && count > 0) {
                    log.info("课程已收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "已收藏", true);
                }
            } catch (Exception e) {
                log.error("检查课程收藏状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
                System.out.println("检查课程收藏状态异常详细信息：");
                e.printStackTrace();
            }
            
            // 添加收藏
            try {
                CourseLike like = new CourseLike();
                like.setCourseId(courseId);
                like.setStudentId(studentId);
                like.setCreatedAt(LocalDateTime.now());
                
                int result = courseLikeMapper.insert(like);
                if (result > 0) {
                    log.info("添加课程收藏成功 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    // 日志记录
                    User user = userService.getById(studentId);
                    String username = user != null ? user.getUsername() : null;
                    String ip = request.getRemoteAddr();
                    String userAgent = request.getHeader("User-Agent");
                    logService.recordCourseLike(studentId, username, courseId, course.getTitle(), ip, userAgent, true);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "收藏成功", true);
                } else {
                    log.warn("添加课程收藏失败 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "收藏失败");
                }
            } catch (Exception e) {
                log.error("添加课程收藏记录异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
                System.out.println("添加课程收藏记录异常详细信息：");
                e.printStackTrace();
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "收藏失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("添加课程收藏异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("添加课程收藏异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "收藏失败: " + e.getMessage());
        }
    }

    /**
     * 取消课程收藏
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @param request HttpServletRequest
     * @return 操作结果
     */
    @DeleteMapping("/{courseId}/like")
    public CommonResponse<Boolean> removeLike(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId,
            HttpServletRequest request) {
        log.info("取消课程收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("取消课程收藏失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("取消课程收藏失败 - 课程不存在, 课程ID: {}", courseId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            // 检查是否已收藏
            try {
                QueryWrapper<CourseLike> checkWrapper = new QueryWrapper<>();
                checkWrapper.eq("course_id", courseId).eq("student_id", studentId);
                Long count = courseLikeMapper.selectCount(checkWrapper);
                
                if (count == null || count == 0) {
                    log.info("取消课程收藏失败 - 未收藏过, 课程ID: {}, 学生ID: {}", courseId, studentId);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "未收藏过该课程", true);
                }
            } catch (Exception e) {
                log.error("检查课程收藏状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
                System.out.println("检查课程收藏状态异常详细信息：");
                e.printStackTrace();
            }
            
            // 删除收藏记录
            try {
                QueryWrapper<CourseLike> wrapper = new QueryWrapper<>();
                wrapper.eq("course_id", courseId).eq("student_id", studentId);
                
                int result = courseLikeMapper.delete(wrapper);
                if (result > 0) {
                    log.info("取消课程收藏成功 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    // 日志记录
                    User user = userService.getById(studentId);
                    String username = user != null ? user.getUsername() : null;
                    String ip = request.getRemoteAddr();
                    String userAgent = request.getHeader("User-Agent");
                    logService.recordCourseLike(studentId, username, courseId, course.getTitle(), ip, userAgent, false);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "取消收藏成功", true);
                } else {
                    log.warn("取消课程收藏失败 - 课程ID: {}, 学生ID: {}", courseId, studentId);
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消收藏失败");
                }
            } catch (Exception e) {
                log.error("删除课程收藏记录异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
                System.out.println("删除课程收藏记录异常详细信息：");
                e.printStackTrace();
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消收藏失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("取消课程收藏异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("取消课程收藏异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消收藏失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否已收藏课程
     * @param courseId 课程ID
     * @param studentId 学生ID
     * @return 是否已收藏
     */
    @GetMapping("/{courseId}/like")
    public CommonResponse<Boolean> isLiked(
            @PathVariable Integer courseId,
            @RequestParam Integer studentId) {
        log.info("检查课程是否已收藏 - 课程ID: {}, 学生ID: {}", courseId, studentId);
        
        try {
            // 参数校验
            if (courseId == null || studentId == null) {
                log.error("检查课程收藏状态失败 - 参数为空, 课程ID: {}, 学生ID: {}", courseId, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数不能为空");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(courseId);
            if (course == null) {
                log.warn("检查课程收藏状态失败 - 课程不存在, 课程ID: {}", courseId);
                // 当课程不存在时，返回未收藏状态而不是错误，避免前端显示错误
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "课程不存在", false);
            }
            
            try {
                QueryWrapper<CourseLike> wrapper = new QueryWrapper<>();
                wrapper.eq("course_id", courseId).eq("student_id", studentId);
                Long count = courseLikeMapper.selectCount(wrapper);
                
                boolean isLiked = count != null && count > 0;
                log.info("课程收藏状态 - 课程ID: {}, 学生ID: {}, 是否已收藏: {}", courseId, studentId, isLiked);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", isLiked);
            } catch (Exception e) {
                log.error("查询课程收藏记录异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
                System.out.println("查询课程收藏记录异常详细信息：");
                e.printStackTrace();
                // 当查询异常时，返回未收藏状态而不是错误，避免前端显示错误
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询异常，默认未收藏", false);
            }
        } catch (Exception e) {
            log.error("查询课程收藏状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", courseId, studentId, e.getMessage());
            System.out.println("查询课程收藏状态异常详细信息：");
            e.printStackTrace();
            // 当发生异常时，返回未收藏状态而不是错误，避免前端显示错误
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询异常，默认未收藏", false);
        }
    }
}